package com.huluobo.appbase.network

import android.widget.Toast
import com.huluobo.appbase.BaseApplication
import com.huluobo.appbase.R
import com.huluobo.appbase.utils.ToastUtil
import kotlinx.coroutines.CancellationException
import retrofit2.HttpException
import java.io.IOException
import java.net.SocketException
import java.net.SocketTimeoutException

/**
 * Created by lc on 2023/3/1.
 * 网络连接统一异常管理类
 */
object HttpErrorDeal {
    fun delHttpError(error: Throwable, deal: (() -> Unit)? = null) {
        when (error) {
            is SocketException -> {
                ToastUtil.shortShow(BaseApplication.context.getString(R.string.server_connection_abnormal))
            }

            is HttpException -> {
                ToastUtil.shortShow(BaseApplication.context.getString(R.string.server_connection_failed))
            }

            is SocketTimeoutException -> {
                ToastUtil.shortShow(BaseApplication.context.getString(R.string.request_timed_out))
            }

            is IOException -> {
                ToastUtil.shortShow(BaseApplication.context.getString(R.string.server_connection_failed))
            }

            is CancellationException -> {
                //协程被取消的异常,这是正常的,不做提示
            }

            else -> {
                error.message?.let {
                    if (it.isNotEmpty()) {
                        ToastUtil.shortShow(it)
                    } else {
                        ToastUtil.shortShow(BaseApplication.context.getString(R.string.null_pointer_exception))
                    }
                }
            }

            //在提示完用户之后,可以把log日志上传到服务器
        }
    }
}